package com.starxg.m3u8.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * ApplicationConfig
 * 
 * @author huangxingguang@lvmama.com
 * @date 2020-08-11 18:44
 */
@Slf4j
@Getter
public class ApplicationConfig {

    /**
     * 默认配置文件路径
     */
    public static final String DEFAULT_SYNC_FILE = "conf" + File.separator + "m3u8-download.conf";

    /**
     * 当前版本
     */
    public static final String VERSION;

    static {
        Properties properties = new Properties();
        try {
            properties.load(ApplicationConfig.class.getResourceAsStream("/application.properties"));
            log.info("读取 [application.properties] 成功。value:{}", properties);
        } catch (IOException e) {
            log.info("读取 [application.properties] 失败。", e);
            System.exit(0);
        } finally {
            VERSION = properties.getProperty("version");
        }
    }

    private static ApplicationConfig instance;

    private transient File syncFile;
    private AppConfig app;
    private WindowConfig window;

    private ApplicationConfig(File syncFile) {
        this.syncFile = syncFile;
    }

    public static ApplicationConfig to(File file) {
        ApplicationConfig applicationConfig = new ApplicationConfig(file);
        try {

            log.info("读取配置 [{}]", file.getAbsolutePath());
            JSONObject json = JSON.parseObject(IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8));
            AppConfig app = json.getJSONObject("app").toJavaObject(AppConfig.class);
            if (app != null) {
                applicationConfig.app = app;
            }
            WindowConfig window = json.getJSONObject("window").toJavaObject(WindowConfig.class);
            if (window != null) {
                applicationConfig.window = window;
            }
            log.info("配置读取成功：{}", JSON.toJSONString(applicationConfig));
        } catch (Exception e) {
            applicationConfig.app = new AppConfig();
            applicationConfig.window = new WindowConfig();
            log.warn("获取配置文件失败，采用默认配置。原因：{}", e.getMessage());
        }

        return instance = applicationConfig;
    }

    public void sync() throws IOException {
        log.info("持久化配置到 [{}]", syncFile.getAbsolutePath());
        if (!this.syncFile.getParentFile().exists() && !this.syncFile.getParentFile().mkdirs()) {
            log.info("持久化失败，原因 ：无法创建文件夹 [{}]", syncFile.getParentFile().getAbsolutePath());
        }
        IOUtils.write(JSON.toJSONString(this, SerializerFeature.PrettyFormat), new FileOutputStream(syncFile),
                StandardCharsets.UTF_8);
    }

    public static ApplicationConfig getInstance() {
        if (instance == null) {
            synchronized (ApplicationConfig.class) {
                if (instance == null) {
                    instance = to(new File(DEFAULT_SYNC_FILE));
                }
            }
        }
        return Objects.requireNonNull(instance);
    }

}
